package com.hero.tweaks.ui.fragments;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.Button;
import com.hero.tweaks.R;
import com.hero.tweaks.util.AxisPreferenceFragment;
import com.hero.tweaks.util.CMDProcessor;
import com.hero.tweaks.util.Constants;
import com.hero.tweaks.util.Helpers;
import android.app.ProgressDialog;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceScreen;
import android.app.AlertDialog;

public class Tools extends AxisPreferenceFragment implements
		OnSharedPreferenceChangeListener, OnPreferenceClickListener, Constants {

	private class DBoptimOperation extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			new CMDProcessor().su.runWaitFor(SH_PATH);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			isrun = false;
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		}

		@Override
		protected void onPreExecute() {
			isrun = true;
			tip = 2;
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setMessage(getString(R.string.optim_db_title));
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.show();
			mPreferences.edit()
					.putLong(PREF_OPTIM_DB, System.currentTimeMillis())
					.commit();
			Helpers.shWrite(getActivity().getFilesDir() + "/sql_optimize");
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	private class FixPermissionsOperation extends
			AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			new CMDProcessor().su.runWaitFor(SH_PATH);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			isrun = false;
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		}

		@Override
		protected void onPreExecute() {
			isrun = true;
			tip = 1;
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setMessage(getString(R.string.fix_perms_title));
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.show();
			Helpers.shWrite(getActivity().getFilesDir() + "/fix_permissions");
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	class fpListener implements View.OnClickListener {
		private final Dialog dialog;

		public fpListener(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View v) {
			dialog.cancel();
			new FixPermissionsOperation().execute();
		}

	}


	class sqlListener implements View.OnClickListener {
		private final Dialog dialog;

		public sqlListener(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View v) {
			dialog.cancel();
			new DBoptimOperation().execute();
		}
	}

	class WipeCacheListener implements View.OnClickListener {
		private final Dialog dialog;

		public WipeCacheListener(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View v) {
			dialog.cancel();
			new WipeCacheOperation().execute();
		}
	}

	private class WipeCacheOperation extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			final StringBuilder sb = new StringBuilder();
			sb.append("busybox rm -rf /data/dalvik-cache/*\n");
			sb.append("busybox rm -rf /cache/*\n");
			Helpers.shExec(sb);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			isrun = false;
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		}

		@Override
		protected void onPreExecute() {
			isrun = true;
			tip = 0;
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setMessage(getString(R.string.wipe_cache_title));
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.show();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	class ZipalignListener implements View.OnClickListener {
		private final Dialog dialog;

		public ZipalignListener(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View v) {
			dialog.cancel();
			new ZipalignOperation().execute();
		}

	}

	private class ZipalignOperation extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			new CMDProcessor().su.runWaitFor(SH_PATH);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			isrun = false;
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		}

		@Override
		protected void onPreExecute() {
			isrun = true;
			tip = 1;
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setMessage(getString(R.string.zipalign_title));
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.show();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	private byte tip;
	SharedPreferences mPreferences;

	private Boolean isrun = false;

	private ProgressDialog progressDialog;

	private Preference mResidualFiles;

	private Preference mOptimDB;

	public Preference normal;

	public Preference recovery;

	public Preference bootloader;

	public Preference hotreboot;

	public PowerManager pm;

	public void Hreboot() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				getActivity());
		// set title
		alertDialogBuilder.setTitle("Hot Reboot");
		// set dialog message
		alertDialogBuilder
				.setMessage(
						"Your device will now restart the shell. Continue with the operation?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							@SuppressWarnings("deprecation")
							@Override
							public void onClick(DialogInterface dialog, int id) {
								CMDProcessor
										.runSuCommand("setprop ctl.restart zygote");
							}
						})
				.setNeutralButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (isrun) {
			switch (tip) {
			case 0:
				progressDialog = ProgressDialog.show(getActivity(),
						getString(R.string.wipe_cache_title),
						getString(R.string.wait));
				progressDialog
						.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				break;
			case 1:
				progressDialog = ProgressDialog.show(getActivity(),
						getString(R.string.fix_perms_title),
						getString(R.string.wait));
				progressDialog
						.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				break;
			case 2:
				progressDialog = ProgressDialog.show(getActivity(),
						getString(R.string.optim_db_title),
						getString(R.string.wait));
				progressDialog
						.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				break;
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mPreferences = PreferenceManager
				.getDefaultSharedPreferences(getActivity());
		mPreferences.registerOnSharedPreferenceChangeListener(this);
		addPreferencesFromResource(R.xml.prefs_tools);

		mOptimDB = findPreference(PREF_OPTIM_DB);

		long mStartTime = mPreferences.getLong(PREF_OPTIM_DB, 0);
		mOptimDB.setSummary("");
		if (mStartTime > 0)
			mOptimDB.setSummary(DateUtils.getRelativeTimeSpanString(mStartTime));
		setRetainInstance(true);

		normal = findPreference("normal");
		normal.setOnPreferenceClickListener(this);

		recovery = findPreference("recovery");
		recovery.setOnPreferenceClickListener(this);

		bootloader = findPreference("bootloader");
		bootloader.setOnPreferenceClickListener(this);

		hotreboot = findPreference("hotreboot");
		hotreboot.setOnPreferenceClickListener(this);

		pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
	}

	@Override
	public void onDetach() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
		super.onDetach();
	}

	@Override
	public boolean onPreferenceClick(Preference pref) {
		// TODO Auto-generated method stub
		if (pref == normal) {
			reboot("");
		}
		if (pref == recovery) {
			reboot("recovery");
		}
		if (pref == bootloader) {
			reboot("bootloader");
		}
		if (pref == hotreboot) {
			Hreboot();
		}
		return false;
	}

	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		String key = preference.getKey();

		if (key.equals(PREF_ZIPALIGN)) {

			AlertDialog.Builder builder = new AlertDialog.Builder(
					getActivity());
			Helpers.get_assetsScript("zipalign", getActivity(), "#", "");
			builder.setTitle(getString(R.string.zipalign_title))
					.setMessage(getString(R.string.wipe_cache_msg))
					.setNegativeButton(getString(R.string.cancel),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							})
					.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {

								}
							});

			AlertDialog alertDialog = builder.create();
			alertDialog.show();
			// alertDialog.setCancelable(false);
			Button theButton = alertDialog
					.getButton(DialogInterface.BUTTON_POSITIVE);
			theButton.setOnClickListener(new ZipalignListener(alertDialog));

		} else if (key.equals(PREF_WIPE_CACHE)) {

			AlertDialog.Builder builder = new AlertDialog.Builder(
					getActivity());
			builder.setTitle(getString(R.string.wipe_cache_title))
					.setMessage(getString(R.string.zipalign_msg))
					.setNegativeButton(getString(R.string.cancel),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							})
					.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {

								}
							});

			AlertDialog alertDialog = builder.create();
			alertDialog.show();
			// alertDialog.setCancelable(false);
			Button theButton = alertDialog
					.getButton(DialogInterface.BUTTON_POSITIVE);
			theButton.setOnClickListener(new WipeCacheListener(alertDialog));

		}

		else if (key.equals(PREF_FIX_PERMS)) {
			Helpers.get_assetsScript("fix_permissions", getActivity(), "#", "");
			AlertDialog.Builder builder = new AlertDialog.Builder(
					getActivity());
			builder.setTitle(getString(R.string.fix_perms_title))
					.setMessage(getString(R.string.fix_perms_msg))
					.setNegativeButton(getString(R.string.cancel),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							})
					.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {

								}
							});

			AlertDialog alertDialog = builder.create();
			alertDialog.show();
			// alertDialog.setCancelable(false);

			Button theButton = alertDialog
					.getButton(DialogInterface.BUTTON_POSITIVE);
			theButton.setOnClickListener(new fpListener(alertDialog));

		} else if (key.equals(PREF_OPTIM_DB)) {
			Helpers.get_assetsScript("sql_optimize", getActivity(), "#", "");
			AlertDialog.Builder builder = new AlertDialog.Builder(
					getActivity());
			builder.setTitle(getString(R.string.optim_db_title))
					.setMessage(
							getString(R.string.ps_optim_db) + "\n\n"
									+ getString(R.string.fix_perms_msg))
					.setNegativeButton(getString(R.string.cancel),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							})
					.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {

								}
							});

			AlertDialog alertDialog = builder.create();
			alertDialog.show();
			// alertDialog.setCancelable(false);

			Button theButton = alertDialog
					.getButton(DialogInterface.BUTTON_POSITIVE);
			theButton.setOnClickListener(new sqlListener(alertDialog));
		}
		return super.onPreferenceTreeClick(preferenceScreen, preference);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if (key.equals(RESIDUAL_FILES)) {
			mResidualFiles.setSummary("");
			final long mStartTime = sharedPreferences.getLong(key, 0);
			if (mStartTime > 0)
				mResidualFiles.setSummary(DateUtils
						.getRelativeTimeSpanString(mStartTime));

		} else if (key.equals(PREF_OPTIM_DB)) {
			mOptimDB.setSummary("");
			final long mStartTime = sharedPreferences.getLong(key, 0);
			if (mStartTime > 0)
				mOptimDB.setSummary(DateUtils
						.getRelativeTimeSpanString(mStartTime));
		}

	}

	public void reboot(final String reason) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				getActivity());
		// set title
		alertDialogBuilder.setTitle("Reboot");
		// set dialog message
		alertDialogBuilder
				.setMessage(
						"Your device will now reboot. Continue with the operation?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								pm.reboot(reason);
							}
						})
				.setNeutralButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}

}
